package design_6_adapter.demo1.handler.impl;

import design_6_adapter.demo1.config.MultiActionController;
import design_6_adapter.demo1.handler.HandlerAdapter;
import design_6_adapter.demo1.util.ControllerBendUtil;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 继承 MultiActionController 的适配器
 *
 * @author wangsong
 * @email 1720696548@qq.com
 * @date 2022/4/13 9:57
 */
public class SimpleControllerHandlerAdapter implements HandlerAdapter {

	private final static String MAPPING = "MAPPING";
	private final static String CLASS_INFO = "CLASS_INFO";


	@Override
	public boolean supports(String uri) {
		Map<Object, Object> method = getClassAndMethod(uri);
		return method != null;
	}

	@Override
	public Object handle(String uri) {
		Map<Object, Object> map = getClassAndMethod(uri);
		Method method = (Method) map.get(MAPPING);
		Class<?> classInfo = (Class) map.get(CLASS_INFO);
		try {
			return method.invoke(classInfo.newInstance());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}


	private Map<Object, Object> getClassAndMethod(String uri) {
		List<Class<?>> controllerBend = ControllerBendUtil.getControllerBend();
		for (Class<?> classInfo : controllerBend) {
			if (classInfo.getSuperclass() == MultiActionController.class) {
				Method[] declaredMethods = classInfo.getDeclaredMethods();
				for (int i = 0; i < declaredMethods.length; i++) {
					// 判断是否有和请求相同的接口地址
					Method declaredMethod = declaredMethods[i];
					if (declaredMethod.getName().equals(uri.substring(1))) {
						Map<Object, Object> map = new HashMap<>();
						map.put(MAPPING, declaredMethods[i]);
						map.put(CLASS_INFO, classInfo);
						return map;
					}
				}
			}
		}
		return null;
	}
}
